package com.ruiysoft.service.sys.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruiysoft.controller.sys.dto.CalculationDto;
import com.ruiysoft.controller.sys.res.CalculationResponse;
import com.ruiysoft.entity.order.OrderMain;
import com.ruiysoft.entity.order.OrderRelationCommission;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysShopDistribution;
import com.ruiysoft.entity.sys.SysShopPersonnelRelation;
import com.ruiysoft.entity.sys.SysUser;
import com.ruiysoft.entity.sys.SysUserShopRelation;
import com.ruiysoft.mapper.order.OrderRelationCommissionMapper;
import com.ruiysoft.mapper.sys.SysMicroShopMapper;
import com.ruiysoft.mapper.sys.SysShopDistributionMapper;
import com.ruiysoft.mapper.sys.SysShopPersonnelRelationMapper;
import com.ruiysoft.mapper.sys.SysUserMapper;
import com.ruiysoft.mapper.sys.SysUserShopRelationMapper;
import com.ruiysoft.service.order.IOrderRelationCommissionService;
import com.ruiysoft.service.sys.ISysMicroShopService;
import com.ruiysoft.service.sys.ISysShopDistributionService;
import com.ruiysoft.service.sys.redis.IRedisSysMicroShopService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huazengguang
 * @since 2018-10-27
 */
@Service
public class SysMicroShopServiceImpl extends ServiceImpl<SysMicroShopMapper, SysMicroShop> implements ISysMicroShopService {

    @Resource
    SysMicroShopMapper sysMicroShopMapper;

    @Resource
    SysShopPersonnelRelationMapper relationMapper;

    @Resource
    SysUserShopRelationMapper userShopRelationMapper;

    @Resource
    SysShopDistributionMapper sysShopDistributionMapper;

    @Resource
    IRedisSysMicroShopService iRedisSysMicroShopService;

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    ISysShopDistributionService iSysShopDistributionService;

    @Resource
    IOrderRelationCommissionService orderRelationCommissionService;

    @Override
    public List<CalculationResponse> calculation(SysShopDistribution distribution, @Valid CalculationDto calculationDto, List<CalculationResponse> responses) {
        System.out.println("店铺主键:"+calculationDto.getShopId()+"--人员信息主键:"+calculationDto.getPersonnelId());
        //获取上级分销关系
        SysShopPersonnelRelation relation = relationMapper.selectOne(new QueryWrapper<SysShopPersonnelRelation>().eq("shop_id",calculationDto.getShopId()).eq("personnel_id",calculationDto.getPersonnelId()));
        Assert.notNull(relation,"没有获取到人员店铺关系");
        Assert.notNull(relation.getParentId(),"没有获取到人员店铺关系");
        SysUserShopRelation userShopRelation = userShopRelationMapper.selectOne(new QueryWrapper<SysUserShopRelation>().eq("shop_id",calculationDto.getShopId()));
        SysUser sysUser = sysUserMapper.selectById(userShopRelation.getUserId());
        if (sysUser.getPersonnelId().equals(calculationDto.getPersonnelId())){
            return responses;
        }
        //计算一级分销
        if (null != relation.getParentId()){
            calculationAmount(distribution.getFirstRatio(),calculationDto.getShopId(),relation.getParentId(),calculationDto.getAmount(),responses);

            SysShopPersonnelRelation parentRelation = relationMapper.selectOne(new QueryWrapper<SysShopPersonnelRelation>().eq("shop_id",calculationDto.getShopId()).eq("parent_id",relation.getParentId()));
            if (null != parentRelation.getParentId()){
                calculationAmount(distribution.getSecondRatio(),calculationDto.getShopId(),parentRelation.getParentId(),calculationDto.getAmount(), responses);
            }
        }
        return responses;
    }

    /**
     * 魏雪刚-分销计算
     * @param orderMain
     * @return
     */
    @Override
    public List<CalculationResponse> calculationWxg(OrderMain orderMain) {
        System.out.println("店铺主键:"+orderMain.getShopId()+"--++++++++++++++++++++++人员信息主键:"+orderMain.getUserId());

        //获取分销比例
        SysShopDistribution distribution = iSysShopDistributionService.getOne(new QueryWrapper<SysShopDistribution>().eq("shop_id",orderMain.getShopId()).eq("defaultFlag",1).le("create_time",orderMain.getPayTime()).orderBy(false,false,"create_time").last("limit 1"));

        //获取上级分销关系
        SysShopPersonnelRelation relation = relationMapper.selectOne(new QueryWrapper<SysShopPersonnelRelation>().eq("shop_id",orderMain.getShopId()).eq("personnel_id",orderMain.getUserId()));
        System.out.println("上下级分销规则---------"+relation.getParentId()+"_______"+relation.getPersonnelId()+"____"+relation.getDistributionId());
        Assert.notNull(relation,"没有获取到人员店铺关系");
        Assert.notNull(relation.getParentId(),"没有获取到人员店铺关系");
//        SysUserShopRelation userShopRelation = userShopRelationMapper.selectOne(new QueryWrapper<SysUserShopRelation>().eq("user_id",orderMain.getUserId()).eq("shop_id",orderMain.getShopId()));
//        SysUser sysUser = sysUserMapper.selectById(userShopRelation.getUserId());
//        System.out.println("1111111111111111111111111");
//        if (sysUser.getPersonnelId().equals(orderMain.getUserId())){
//            return null;
//        }
        System.out.println("2222222222222222222222");
        //计算一级分销
        if (null != relation.getParentId() && relation.getParentId()!=0){
            System.out.println("33333333333333333333333");
            SysShopPersonnelRelation relationP=relationMapper.selectOne(new QueryWrapper<SysShopPersonnelRelation>().eq("shop_id",orderMain.getShopId()).eq("personnel_id",relation.getParentId()));
            System.out.println("4444444444444444444444");
            if(relationP!=null && relationP.getDistributionId()!=0){
                System.out.println("5555555555555555555555555555");
                SysShopDistribution distribution1=iSysShopDistributionService.getById(relationP.getDistributionId());
                System.out.println("distribution1---------------------"+distribution1.getFirstRatio()+"+++++"+relation.getParentId());
                calculationAmountWxg(distribution1.getFirstRatio(),orderMain,relation.getParentId(),orderMain.getTotalAmount(),2,distribution1.getId());
            }else{
                System.out.println("6666666666666666666666666666");
                if(distribution!=null){
                    calculationAmountWxg(distribution.getFirstRatio(),orderMain,relation.getParentId(),orderMain.getTotalAmount(),2,distribution.getId());
                }

            }
            System.out.println("77777777777777777777777777777777");
//            SysShopPersonnelRelation parentRelation = relationMapper.selectOne(new QueryWrapper<SysShopPersonnelRelation>().eq("shop_id",orderMain.getShopId()).eq("personnel_id",relationP.getParentId()));

//            if(parentRelations!=null){
//                SysShopPersonnelRelation parentRelation=parentRelations.get(0);
//            }
//            SysShopPersonnelRelation parentRelation=parentRelations.get(0);
            System.out.println("88888888888888888888888888888888");
            if (null != relationP.getParentId() && relationP.getParentId()!=0){
                System.out.println("9999999999999999999999999999999");
                relationP=relationMapper.selectOne(new QueryWrapper<SysShopPersonnelRelation>().eq("shop_id",orderMain.getShopId()).eq("personnel_id",relationP.getParentId()));
                System.out.println("000000000000000000000000000000000000");
                if(relationP!=null && relationP.getDistributionId()!=0){
                    SysShopDistribution distribution1=iSysShopDistributionService.getById(relationP.getDistributionId());
                    calculationAmountWxg(distribution1.getSecondRatio(),orderMain,relationP.getParentId(),orderMain.getTotalAmount(),1,distribution1.getId());
                }else{
                    if(distribution!=null) {
                        calculationAmountWxg(distribution.getSecondRatio(), orderMain, relationP.getParentId(), orderMain.getTotalAmount(), 1, distribution.getId());
                    }
            }}
        }
        return null;
    }

    @Override
    public SysMicroShop selectSysMicroShopById(Long shopId) {
        return iRedisSysMicroShopService.selectSysMicroShopById(shopId);
    }

    @Override
    public void clearSysMicroShopById(Long id) {
        iRedisSysMicroShopService.clearSysMicroShopById(id);
    }

    private void calculationAmount(BigDecimal ratio, Long shopId, Long personnelId, BigDecimal amount, List<CalculationResponse> responses) {
        if (ratio.compareTo(BigDecimal.ZERO)== 1){
            CalculationResponse response = new CalculationResponse();
            //计算一级分销
            response.setShopId(shopId);
            response.setPersonnelId(personnelId);
            response.setAmount(amount.multiply(ratio.divide(new BigDecimal(100))));
            responses.add(response);
        }
    }

    private void calculationAmountWxg(BigDecimal ratio, OrderMain orderMain, Long personnelId, long amount,int relationLevel,long distributionRuleId) {
        System.out.println("pppppppppppppppppppppppppppppppppppp");
        if (ratio.compareTo(BigDecimal.ZERO)== 1){//如果分成比例不为空,则计算并插入表
            System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu");
            OrderRelationCommission relationCommission=new OrderRelationCommission();
            relationCommission.setOrderAmount(orderMain.getTotalAmount()).setOrderId(orderMain.getId()).setOrderCode(orderMain.getOrderNo())
            .setBuyerId(orderMain.getUserId()).setCreateTime(LocalDateTime.now()).setRatio(ratio).setShopId(orderMain.getShopId()).setUserId(personnelId)
            .setRelationLevel(relationLevel).setDistributionRuleId(distributionRuleId);
            relationCommission.setAmount((new BigDecimal(orderMain.getTotalAmount()).multiply(ratio)).longValue());
            orderRelationCommissionService.save(relationCommission);
        }

    }
}
